package com.ck.controller.admin;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.ck.domain.Admin;
import com.ck.service.AdminService;

public class EditAdminOwnPasswordController extends SimpleFormController {
	
	private AdminService adminService;

	public void setAdminService(AdminService adminService) {
		this.adminService = adminService;
	}
	
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {

		Admin admin = (Admin) command;
		Map model = errors.getModel();
		
		//后台校验
		boolean flag = true;
		String oldPassword = request.getParameter("oldPassword").trim();
		String password = admin.getPassword().trim();
        String confirmPassword = request.getParameter("confirmPassword").trim();
        
        if(oldPassword == null || "".equals(oldPassword)) {
			model.put("error_oldPassword", "请输入原密码");
			flag = false;
		}
        if(password == null || "".equals(password)) {
			model.put("error_password", "请输入新密码");
			flag = false;
		}
        if(password.length() > 32) {
			model.put("error_password", "新密码长度：1-32个字符");
			flag = false;
		}
        if(confirmPassword == null || "".equals(confirmPassword)) {
			model.put("error_confirmPassword", "请输入确认密码");
			flag = false;
		}
        boolean isSamePassword = adminService.validatePassword(admin, confirmPassword, model);
        if (!isSamePassword) {
        	flag = false;
        }
        
        //校验不通过
        if(!flag){
        	model.put("oldPassword", oldPassword);
        	model.put("password", password);
        	model.put("confirmPassword", confirmPassword);
			return new ModelAndView(getFormView(), model);
		}
        
        admin.setId((Integer)request.getSession().getAttribute("adminID"));
        model.put("admin", admin);
        
        //修改密码
        boolean isSuccessModified = adminService.editAdminOwnPassword(oldPassword, admin, model);
        
        if (isSuccessModified) {
            return new ModelAndView(getSuccessView(), model);
        } else {
        	model.put("oldPassword", oldPassword);
        	model.put("password", password);
        	model.put("confirmPassword", confirmPassword);
            return new ModelAndView(getFormView(), model);
        }
	}
	
}
